<template>
  <el-container class="main-layout">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '240px'" class="main-aside">
      <div class="logo-container">
        <el-icon v-if="!isCollapse" :size="28" color="#409eff">
          <Trophy />
        </el-icon>
        <span v-if="!isCollapse" class="logo-text">军事数据加工平台</span>
      </div>

      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :unique-opened="true"
        router
        class="main-menu"
      >
        <template v-for="route in menuRoutes" :key="route.path">
          <!-- 没有子菜单 -->
          <el-menu-item
            v-if="!route.children || route.children.length === 0"
            :index="`/${route.path}`"
          >
            <el-icon><component :is="route.meta?.icon" /></el-icon>
            <template #title>{{ route.meta?.title }}</template>
          </el-menu-item>

          <!-- 有子菜单 -->
          <el-sub-menu v-else :index="route.path">
            <template #title>
              <el-icon><component :is="route.meta?.icon" /></el-icon>
              <span>{{ route.meta?.title }}</span>
            </template>
            <el-menu-item
              v-for="child in route.children"
              :key="child.path"
              :index="`/${child.path}`"
            >
              <template #title>{{ child.meta?.title }}</template>
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>

      <div class="collapse-btn" @click="toggleCollapse">
        <el-icon>
          <Fold v-if="!isCollapse" />
          <Expand v-else />
        </el-icon>
      </div>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部导航 -->
      <el-header class="main-header">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item
              v-for="item in breadcrumbs"
              :key="item.path"
              :to="item.path"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="header-right">
          <el-badge :value="systemStore.stats.pending_audit" :max="99" class="item">
            <el-button :icon="Bell" circle />
          </el-badge>
          
          <el-dropdown @command="handleCommand">
            <div class="user-info">
              <el-avatar :size="32" :icon="UserFilled" />
              <span class="username">{{ userStore.userInfo?.realName }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item disabled>
                  <div>
                    <div>{{ userStore.userInfo?.realName }}</div>
                    <div style="font-size: 12px; color: #909399;">{{ userStore.userInfo?.employeeId }}</div>
                  </div>
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 内容区 -->
      <el-main class="main-content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSystemStore } from '@/stores/system'
import { useUserStore } from '@/stores/user'
import { Bell, UserFilled } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const systemStore = useSystemStore()
const userStore = useUserStore()

const isCollapse = ref(false)

// 构建菜单树
const menuRoutes = computed(() => {
  const routes = route.matched[0]?.children?.filter(r => r.path !== 'dashboard') || []
  
  // 按模块分组
  const menuMap = new Map()
  
  routes.forEach(r => {
    const pathParts = r.path.split('/')
    const module = pathParts[0]
    const subPath = pathParts[1]
    
    if (!menuMap.has(module)) {
      menuMap.set(module, {
        path: module,
        name: module.charAt(0).toUpperCase() + module.slice(1),
        meta: r.meta,
        children: []
      })
    }
    
    if (subPath) {
      menuMap.get(module).children.push({
        path: r.path,
        name: r.name,
        meta: { ...r.meta, title: r.meta.subtitle || r.meta.title }
      })
    }
  })
  
  return Array.from(menuMap.values())
})

// 当前激活菜单
const activeMenu = computed(() => {
  const { path } = route
  // 确保返回完整路径，以 / 开头
  return path.startsWith('/') ? path : `/${path}`
})

// 面包屑
const breadcrumbs = computed(() => {
  const matched = route.matched.filter(r => r.meta?.title)
  return matched.map(r => ({
    path: r.path,
    title: r.meta.title
  }))
})

// 切换侧边栏
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/login')
    } catch {
      // 用户取消
    }
  }
}

// 监听路由变化，更新统计数据
watch(() => route.path, () => {
  systemStore.getStatistics()
}, { immediate: true })
</script>

<style lang="scss" scoped>
.main-layout {
  height: 100vh;
}

.main-aside {
  background: #001529;
  transition: width 0.3s;
  display: flex;
  flex-direction: column;

  .logo-container {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: #fff;
    font-size: 18px;
    font-weight: bold;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .logo-text {
      white-space: nowrap;
    }
  }

  .main-menu {
    flex: 1;
    border: none;
    background: #001529;
    overflow-y: auto;

    &:not(.el-menu--collapse) {
      width: 240px;
    }

    // 菜单项样式
    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      color: rgba(255, 255, 255, 0.85);
      
      &:hover {
        background-color: rgba(255, 255, 255, 0.08);
        color: #fff;
      }
    }

    // 激活状态
    :deep(.el-menu-item.is-active) {
      background-color: #1890ff !important;
      color: #fff !important;
    }

    // 子菜单标题
    :deep(.el-sub-menu__title) {
      &:hover {
        background-color: rgba(255, 255, 255, 0.08);
      }
    }

    // 展开的子菜单
    :deep(.el-sub-menu.is-opened) {
      .el-sub-menu__title {
        color: #fff;
      }
    }

    // 子菜单列表
    :deep(.el-menu) {
      background-color: #000c17;
    }

    // 图标颜色
    :deep(.el-icon) {
      color: rgba(255, 255, 255, 0.85);
    }

    :deep(.el-menu-item.is-active .el-icon) {
      color: #fff;
    }
  }

  .collapse-btn {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #fff;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    transition: background 0.3s;

    &:hover {
      background: rgba(255, 255, 255, 0.1);
    }
  }
}

.main-header {
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;

  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      padding: 4px 8px;
      border-radius: 4px;
      transition: background 0.3s;

      &:hover {
        background: #f5f7fa;
      }

      .username {
        font-size: 14px;
        color: #303133;
      }
    }
  }
}

.main-content {
  background: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

